// lose.js
import { CanvasButton } from '../component/custombutton'
export class Lose {
    constructor(canvas, width, height, score, restartCallback, reBackHome) {
        this.canvas = canvas;
        this.context = this.canvas.getContext('2d');
        this.width = width;
        this.height = height;
        this.score = score;

        this.restartCallback = restartCallback;
        this.reBackHome = reBackHome;
        
        this.percentage = 8 / 10;

        this.modelWidth = this.width * this.percentage;
        this.modelHeight = this.height / 2;
        this.modelX = this.width / 10;
        this.modelY = this.height / 4;

        this.size_1 = this.modelWidth * (1 - this.percentage) / 2;
        this.size_2 = this.modelWidth * (1 - this.percentage) / 3;

        this.button = [];

        this.isAnimating = true;

        this.woodSize = this.size_1 * 3 / 2;
        this.woodX = this.width / 2 + this.woodSize;
        this.woodY = this.modelY + this.woodSize;
        this.velocity = 0;
        this.gravity = 0.5;

        this.pigHeight = this.height * (1 - this.percentage) - this.size_1;
        this.pigWidth = this.width * 2 / 3;
        this.pigX = this.width / 2 - this.pigWidth / 2;
        // this.pigY = this.modelY + this.size_1 + this.woodSize * 2;
        this.pigY = this.height * this.percentage - this.size_1 * 5 - this.size_2 * 2 - this.pigHeight;

        this.animationFrameId = null;

        this.woodRotation = 0;
        this.isWoodTilting = false;
        this.tiltSpeed = 0.05;

        this.floorX = this.pigX + this.pigWidth;
        this.floorY = this.pigY + this.pigHeight - this.woodSize;

        this.arcCenterX = (this.woodX + this.floorX) / 2;
        this.arcCenterY = this.woodY;
        this.arcRadius = this.arcCenterX - this.woodX;
        this.arcAngle = 0;

    }

    drawPopup() {
      this.onLoadImage(() => {
            this.drawModal();
            this.drawButton();
            this.drawAnimate();
        })
    }

    drawModal() {
        // 绘制背景图片
        this.context.drawImage(this.background, this.modelX, this.modelY, this.modelWidth, this.modelHeight);        

        this.context.font = `${this.size_1}px Arial`;
        this.context.fillStyle = 'black';
        this.context.textAlign = 'center';
        this.context.fillText('游戏失败', this.width / 2, this.modelY + this.size_1);

        this.context.font = `${this.size_2}px Arial`;
        this.context.fillStyle = 'black';
        this.context.textAlign = 'center';
        this.context.fillText(`您已经完成了${this.score / 2}%`, this.width / 2, this.modelY + this.size_1 * 3);   

        this.context.font = `${this.size_2}px Arial`;
        this.context.fillText('实力不行还得练！', this.width / 2, this.height * this.percentage - this.size_1 * 5 - this.size_2);
    }

    drawAnimate() {
        if(this.isAnimating) {
            this.context.clearRect(this.modelX, this.modelY, this.modelWidth, this.modelHeight);
            this.drawModal();

            // 更新小方块的位置
            this.velocity += this.gravity;
            this.woodY += this.velocity;

            // 检测碰撞
            if (this.woodY >= this.pigY) {
                this.woodY = this.pigY;
                this.velocity = 0;
                this.isWoodTilting = true;
            }

            if (this.isWoodTilting) {
                // this.woodRotation += this.tiltSpeed; // 控制旋转速度
                // if (this.woodRotation >= Math.PI / 2) {
                //     this.woodRotation = Math.PI / 2; // 限制最大旋转角度为90度
                //     this.isWoodTilting = false;
                // }
                // 更新木块位置，使其沿弧线倾斜倒地
                // this.woodX = this.arcCenterX + this.arcRadius * Math.cos(this.arcAngle) - this.woodSize / 2;
                // this.woodY = this.arcCenterY + this.arcRadius * Math.sin(this.arcAngle) - this.woodSize / 2;

                this.drawPig();
                this.pigImageIndex = (this.pigImageIndex + 1) % this.pigImageCnt;
                if (this.pigImageIndex === 0) { 
                    this.woodY = this.modelY + this.woodSize;
                    this.isWoodTilting = false;
                }
                // this.drawTree();
            } else {
                // 绘制
                this.drawLargeBlock();
                this.drawSmallBlock();
            }

        }
        requestAnimationFrame(() => this.drawAnimate());
    }

    drawTree() {
        this.context.save();
        // 将旋转点移至木块中心
        this.context.translate(this.woodX + this.woodSize / 2, this.woodY + this.woodSize / 2);
        this.context.rotate(this.woodRotation); // 旋转
        // 将绘制点移回木块位置
        this.context.translate(-this.woodSize / 2, -this.woodSize / 2);
        this.context.drawImage(this.tree_background, 0, 0, this.woodSize, this.woodSize);
        this.context.restore();
    }

    drawPig() {
        this.context.drawImage(this.pigImage[this.pigImageIndex], this.pigX, this.pigY, this.pigWidth, this.pigHeight);
    }

    drawSmallBlock() {
        // this.context.fillStyle = 'red';
        this.context.drawImage(this.tree_background, this.woodX, this.woodY, this.woodSize, this.woodSize);
    }

    drawLargeBlock() {
        // this.context.fillStyle = 'blue';
        this.context.drawImage(this.pig_background_1, this.pigX, this.pigY, this.pigWidth, this.pigHeight);
    }

    onLoadImage(callback) {
      let loadedCount = 0;
      const totalImages = 23;

      this.background = wx.createImage();
      this.background.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/background/background_3.png';
      this.background.onload = () => {
        loadedCount++;
        checkIfAllLoaded();
      };

      this.tree_background = wx.createImage();
      this.tree_background.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/tree_icon_1.png';
      this.tree_background.onload = () => {
          loadedCount++;
          checkIfAllLoaded();
      };

      this.pig_background_1 = wx.createImage();
      this.pig_background_1.src = 'https://gitee.com/z-l-ya/game-image/raw/master/images/icons/pig1.png';
      this.pig_background_1.onload = () => {
          loadedCount++;
          checkIfAllLoaded();
      };

      this.pigImageAdd = 'https://gitee.com/z-l-ya/game-image/raw/master/images/pig'
      this.pigImageCnt = 20
      this.pigImage = [];
      this.pigImageIndex = 0; 

      for (let i = 0; i < this.pigImageCnt; i++) {
          const img = wx.createImage();
          img.src = `${this.pigImageAdd}/pig_${i + 1}.png`;
          img.onload = () => {
            loadedCount++;
            checkIfAllLoaded();
        };
        this.pigImage.push(img);
      }


      const checkIfAllLoaded = () => {
        if (loadedCount === totalImages && callback) {
          callback();
        }
      };
    }

    drawButton() {
        let _this = this;
        let restart = {
            type: "text",
            text: "重新开始",
            style: {
                backgroundColor: 'blue',
                left: this.width / 4,
                top: this.height * this.percentage - this.size_1 * 5,
                width: this.width / 2,
                height: this.size_1,
                textAlign: 'center',
                fontSize: this.iconSize / 2,
                textColor: "white"
            },
            success(button) {
                _this.button.push(button);
                button.drawButton(_this.context); // 绘制按钮
                button.onTap((res) => {
                    _this.isAnimating = false;   
                    _this.buttonDestroy();
                    _this.restartCallback();
                })
            },
        };
        let reback = {
            type: "text",
            text: "返回主页",
            style: {
                backgroundColor: 'blue',
                left: this.width / 4,
                top: this.height * this.percentage - this.size_1 * 3,
                width: this.width / 2,
                height: this.size_1,
                textAlign: 'center',
                fontSize: this.iconSize / 2,
                textColor: "white"
            },
            success(button) {
                _this.button.push(button);
                button.drawButton(_this.context); // 绘制按钮
                button.onTap((res) => {
                  console.log('失败按钮被点击')
                    _this.isAnimating = false;
                    _this.reBackHome();
                    _this.buttonDestroy();
                })
            },
        };
        new CanvasButton(restart);
        new CanvasButton(reback);
    }

    buttonDestroy() {
        this.button.forEach(bt => {
            bt.destroy();
        });
        // this.button = null;
    }


    // onClick(event) {
    //     const touchX = event.touches[0].clientX;
    //     const touchY = event.touches[0].clientY;
    //     // console.log(touchX,touchY)
    //     // // 点击回到首页按钮
    //     // if (touchX >= this.width / 4 && touchX <= this.width / 4 + this.width / 2 &&
    //     // touchY >= this.height * 2 / 3 && touchY <= this.height * 2 / 3 + 40) {
    //     //     if (typeof this.reBackHome === 'function') {
    //     //         this.reBackHome();
    //     //         this.onlyone = false;
    //     //     }
    //     // // 点击重新开始按钮
    //     // } else if (touchX >= this.width / 4 && touchX <= this.width / 4 + this.width / 2 && 
    //     // touchY >= this.height * 3 / 5 && touchY <= this.height * 3 / 5 + 40) {
    //     //     if (typeof this.restartCallback === 'function') {
    //     //         this.restartCallback();
    //     //         this.onlyone = false;
    //     //     }
    //     // }
    // }

}
